package xin.yangshuai.zookeeper011.case1;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.Random;

public class DistributeServer {

    // 服务器动态上下线
    // 在zookeeper中创建/servers节点，可以使用命令行：create /servers "servers"
    // 服务器上线，在zookeeper上创建服务器节点

    // 注意：逗号左右不能有空格
    private String connectString = "192.168.145.132:2181,192.168.145.133:2181,192.168.145.134:2181";
    // 2000毫秒
    private int sessionTimeout = 2000;

    private ZooKeeper zkClient;

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

        DistributeServer server = new DistributeServer();
        // 1. 连接zookeeper
        server.getConnect();

        // 2. 服务器上线，在zookeeper上创建服务器节点（服务器注册），0到9随机数
        server.regist("server" + new Random().nextInt(10));

        // 3. 启动业务逻辑（保持运行状态）
        server.business();

    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void regist(String hostname) throws KeeperException, InterruptedException {
        // 创建一个带序号的临时节点
        String create = zkClient.create("/servers/" + hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + " is online");
    }

    private void getConnect() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }
}
